package calculatorController;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.StringTokenizer;

import javax.swing.JButton;

import calculatorModel.Operation;
import calculatorView.CalculatorArea;

public class EqualButton extends JButton {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Operation operator;

	private CalculatorArea area;

	public EqualButton(Operation operator, CalculatorArea area) {
		super();
		this.operator = operator;
		this.area = area;
		this.setText("=");
		setEqualButton();
	}

	// se lo metto nel costruttore?

	private void setEqualButton() {

		this.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				verifySequence();

			}

			
		});
	}
	private void verifySequence() {
		//modello e astrazione
		String espression = area.getArea().getText();
		String operand = new String();
		int[] element = new int[2];

		StringTokenizer strtok = new StringTokenizer(espression, " ");
		int verifySeq = strtok.countTokens();
		String operand1 = strtok.nextToken();
		operand = strtok.nextToken();
		String operand2 = strtok.nextToken();
		if (operand1.length() < 11 && operand2.length() < 11) {

			if (verifySeq == 3) {
					//TODO codice ripetuto

				if (operand1.charAt(0) == '-') {
					operand1 = operand1.substring(1);
					element[0] = -Integer.parseInt(operand1);
				} else {

					element[0] = Integer.parseInt(operand1);
				}
				if (operand2.charAt(0) == '-') {
					operand2 = operand2.substring(1);
					element[1] = -Integer.parseInt(operand2);

				} else {
					element[1] = Integer.parseInt(operand2);
				}
				try {
					operator.setResults(operator.getOperator()
							.doIntOperation(element));
				} catch (Exception e1) {
					area.getArea().setText(null);
					area.getArea().setText("Error, divided by zero");
				}
			} else {
				area.getArea().setText(null);
				area.getArea().setText("Error, sequence not followed");
			}
		} else {
			area.getArea().setText(null);
			area.getArea().setText("Numbers too big !");
		}
	}


}
